package com.liner;

import java.util.Random;
import java.util.Scanner;

public class VerificationCode {


    public static void main(String[] args) {
        /*
         * 随机生成 N位 验证码  包含 大写字母、小写字母、数字
         *
         */


        Scanner scanner = new Scanner(System.in);

        System.out.print("请输入生成验证码位数:");
        int num = scanner.nextInt();
        String code = verCode(num);
        System.out.println(code);
        System.out.print("请输入验证码:");
        String verCode = scanner.next();

        if (verCode.equalsIgnoreCase(code)) {
            System.out.println("验证码正确");
        }else {
            System.out.println("验证码错误");
        }


       /* System.out.print("请输入验证码:");
        String code1 = generateVeriCode(num);
        System.out.println(code1);*/

    }

    /**
     * 生成 N位 验证码
     *
     * @param len
     * @return
     */

    public static String verCode(int len) {
        String code = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrlstuvwxyz";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            int index = (int) (Math.random() * code.length());
            sb.append(code.charAt(index));
        }
        return sb.toString();
    }


    /**
     * 验证码 可选范围
     *
     * @param len
     * @return
     */
    public static String generateVeriCode(int len) {
        Random random = new Random();
        String code = "";
        char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
                'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
                'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
        //验证码字符可选范围
        for (int i = 0; i < len; i++) {
            int index = random.nextInt(chars.length); //0到61
            code += chars[index];
        }
        return code;
    }

}
